package com.soar.tbox.protocol;

import java.lang.reflect.Constructor;
import java.util.List;

import com.soar.tbox.CommandStorage;
import com.soar.tbox.DisplayHandler;
import com.soar.tbox.Messenger;
import com.soar.tbox.bean.Command;
import com.soar.tbox.bean.Paramter;
import com.soar.tbox.bean.SmsCommand;
import com.soar.tbox.util.Converts;
import com.soar.tbox.util.LogUtil;
import com.soar.tbox.util.SmsNotifyCommandAnalyzer;

/**
 * 指令分发器.
 * 
 * @author songjunjie
 * 
 */
public class DispatchProtocol {
	/**
	 * 问询指令名
	 */
	private static final String ASK = "FF01";

	@SuppressWarnings("unchecked")
	public static void doDispatch(String sms) {
		SmsCommand smsCommand = null;
		DisplayHandler.show("收到短信通知指令\n"+sms);
		/**
		 *  1.解析短信指令，得到流水号 
		 */
		try {
			smsCommand = SmsNotifyCommandAnalyzer.analyze(sms);
			smsCommand.getCmd();
		} catch (Exception e) {
			LogUtil.error("解析短信指令出现错误。", e);
			e.printStackTrace();
			return;
		}
		String serialNum = smsCommand.getSerialNum();
		
		/**
		 *  2.构造问询指令，将流水号加到问询指令参数中 
		 */
		Command askComman = CommandStorage.getCommand(ASK);
		askComman.setSerialNum(serialNum);

		/** 
		 * 3.建立数据连接，将问询指令发送到网关
		 */
		Messenger messenger = new Messenger();
		Command respCommand = null;
		try {
			respCommand = messenger.send(askComman, true);
		} catch (Exception e) {
			LogUtil.error("发送问询指令到网关出现错误", e);
			e.printStackTrace();
			DisplayHandler.show("发送问询指令到网关出现错误:"+e.getMessage()+"\n");
			return;
		}
		/**
		 * 4.解析返回指令，找到对应的业务指令进行业务处理
		 */
		byte type = respCommand.getType();
		byte cmdno = respCommand.getCommandNo();
		byte[] data = {type,cmdno};
		//指令的名字 指令类型+指令编号
		String cmdName = Converts.printHexBinary(data);
		String className = "com.soar.tbox.protocol.Protocol"+cmdName;
		Class<Protocol> protocolClass;
		try {
			protocolClass = (Class<Protocol>) Class.forName(className,false,DispatchProtocol.class.getClassLoader());
			Constructor<Protocol> constructor = protocolClass.getConstructor(Command.class,String.class);
			Protocol protocol = constructor.newInstance(respCommand,serialNum);
			protocol.handle();
		} catch (ClassNotFoundException e) {
			LogUtil.error("没有找到指令的处理程序.", e);
			e.printStackTrace();
			DisplayHandler.show("没有找到指令的处理程序.指令名："+cmdName+"\n"+e.getMessage()+"\n");
			e.printStackTrace();
		} catch (Exception e) {
			LogUtil.error("", e);
			e.printStackTrace();
			DisplayHandler.show("执行指令出现错误.指令名:"+cmdName+"\n");
		}
	}
}
